var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');

// body-parser: express的Ajax处理
var bodyParser = require('body-parser');

var nunjucks = require('nunjucks');


var routers = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
// 设置引擎模板
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

// 引入模板
var env = nunjucks.configure(app.get('views'), {
  autoescape: false,
  noCache: true,
  watch: true,
  express: app,
});

// 网站icon  似乎不管用
app.use(favicon(path.join(__dirname, '/public/images/fav-icon.ico')));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// 静态文件放置位置
app.use(express.static(path.join(__dirname, 'public')));
// 上下面代码表示当用户使用/访问时，调用routes，即routes目录下的routers.js文件，
//其中.js后缀省略，用/users访问时，调用routes目录下users.js文件
var valiateCookie = function(req, res, next) {
  if (
      !(req.cookies && req.cookies['LoginStatus']) 
      && req.url != '/login' 
      && req.url != '/register') {
    res.redirect('/login')
  } else {
    console.log('LoginStatus', req.cookies && req.cookies['LoginStatus'])
    next()
  }
}
app.use(valiateCookie)
app.use('/', routers);
app.use('/users', users);
// 路由中间件与路由use的位置问题会引起bug


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});


// 如果是开发环境，处理error时会输出堆栈信息
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error', {
    results: err.message
  });
});

module.exports = app;